<!--
 * @Description: 点播视频播放组件
 * @Version: 1.0.0.1
 * @Autor: zhaozhenzhuo
 * @Date: 2025-10-20 15:51:33
 * @LastEditors: zhaozhenzhuo
 * @LastEditTime: 2025-10-20 18:12:55
-->
<template>
	<div class="xg-wrap">
		<div
			v-if="videojsData && videojsData.videoId && !isCovered && !isDelete"
			:id="`XgPlayer${videojsData.videoId}`"
		></div>
		<p v-else-if="isCovered" class="forbidden-wrap">录像文件已被覆盖，请联系管理人员确认</p>
		<p v-else-if="isDelete" class="forbidden-wrap">录像文件已被删除，请联系管理人员确认</p>
		<p v-else class="forbidden-wrap">{{ videoPreviewErrorTis }}</p>
	</div>
</template>

<script setup lang="ts">
import Player from 'xgplayer';
import 'xgplayer/dist/index.min.css';
import { onMounted, onBeforeUnmount, watch, nextTick, ref } from 'vue';
import videoPoster from '@/assets/images/video-poster.png';
import type { XgPlayerProps } from './VideoPlayer.type';

const props = withDefaults(defineProps<XgPlayerProps>(), {
	videojsData: null,
	autoplay: true,
	isVolume: true,
	isCovered: false,
	isDelete: false
});

watch(
	() => props.videojsData,
	async (newV, oldV) => {
		if (oldV && newV?.source) {
			if (newV.videoId === oldV.videoId && player) {
				// 只更换地址
				player.src = newV.source;
			} else {
				if (player) {
					player.destroy();
					player = null;
				}
				await nextTick();
				// 重新初始化播放器
				createPlayer(newV.source);
			}
		}
	},
	{ deep: true }
);

let player: Player | null = null;
const videoPreviewErrorTis = ref('当前无法播放该资源，请检测网络环境或资源地址');
const createPlayer = (url: string) => {
	// 录像被覆盖
	if (props.isCovered || props.isDelete) {
		return;
	}
	player = new Player({
		id: `XgPlayer${props.videojsData?.videoId}`,
		url,
		poster: videoPoster,
		errorTips: videoPreviewErrorTis.value,
		width: '100%',
		height: '100%',
		volume: props.isVolume ? 0.6 : 0,
		autoplay: props.autoplay,
		preloadTime: 1
	});
};

onMounted(() => {
	if (props.videojsData && props.videojsData.source) {
		createPlayer(props.videojsData.source);
	} else {
		player = null;
	}
});
onBeforeUnmount(() => {
	if (player) {
		player.destroy();
	}
});
</script>

<style lang="scss" scoped>
.xg-wrap {
	width: 100%;
	height: 100%;

	.forbidden-wrap {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #000000;
		color: #ffffff;
		font-size: $font-size-small-1;
	}
}
</style>
